package org.groovymud.shell.telnetd;

/* Copyright 2008 Matthew Corby-Eaglen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */

import net.wimpi.telnetd.net.ConnectionEvent;
import net.wimpi.telnetd.shell.Shell;
import org.apache.log4j.Logger;
import org.groovymud.object.alive.Player;
import org.groovymud.object.registry.MudCloneException;
import org.groovymud.object.registry.MudObjectAttendant;
import org.groovymud.object.registry.Registry;
import org.groovymud.shell.delegates.LoginDelegate;
import org.groovymud.shell.io.TerminalIO;
import org.groovymud.shell.io.TerminalIOFactory;

import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.util.HashMap;

/**
 * specific instance of a player connects through this shell
 * <p/>
 * provides JAAS authentication callback functions see
 * http://java.sun.com/j2se/1.4
 * .2/docs/guide/security/jaas/JAASRefGuide.html#Callback
 */

public abstract class LoginShell extends ShellBridge {

    private static final String BEAN_NAME = "loginShell";

    private final static Logger logger = Logger.getLogger(LoginShell.class);
    private final MudObjectAttendant objectAttendant;
    private Player player;

    public LoginShell(final Registry registry, final TerminalIOFactory ioFactory, MudObjectAttendant objectAttendant) {
        super(registry, ioFactory);
        this.objectAttendant = objectAttendant;
    }

    public void doRun() {

        TerminalIO io = getTerminalIO();

        try {
            LoginDelegate delegate = createLoginDelegate();
            delegate.setTerminalIO(io);
            LoginContext lc = delegate.login(this);

            final Registry registry = getRegistry();
            player = (Player) delegate.getCallbackData().get("player");
            registry.addActivePlayer(this, player);
            objectAttendant.savePlayerData(player);
            objectAttendant.moveToLocation(player, player.getContainerLocation());
            HashMap<String, Object> environment = new HashMap<String, Object>();
            environment.put("player", player);
            environment.put("loginContext", lc);
            environment.put("terminalIO", getTerminalIO());

            getConnection().getConnectionData().getEnvironment().putAll(environment);
            getConnection().setNextShell(MudShell.BEAN_NAME);
            getConnection().removeConnectionListener(this);
        } catch (LoginException e) {
            closeConnectionOnException(e, "login failed: ");
        } catch (IOException e) {
            logger.error(e, e);
            closeConnectionOnException(e, "something 'orrd 'appened: ");
        } catch (InstantiationException e) {
            movePlayerToVoid();
        } catch (MudCloneException e) {
            movePlayerToVoid();
        }
    }

    private void closeConnectionOnException(Exception e, String message) {
        try {
            getConnection().getTerminalIO().write(message + e.getMessage());
        } catch (IOException ioe) {
            logger.error("error writing to user terminal closing connection", ioe);
        } finally {
            getConnection().close();
        }
    }

    private void movePlayerToVoid() {
        try {
            objectAttendant.movePlayerToVoid(player);
        } catch (Exception e) {
            closeConnectionOnException(e, "Something horrid went wrong: ");
        }
    }

    public abstract LoginDelegate createLoginDelegate();

    // this implements the ConnectionListener!
    public void connectionTimedOut(ConnectionEvent ce) {
        try {
            getTerminalIO().write("CONNECTION_TIMEDOUT");
            getTerminalIO().flush();
            // close connection
            getConnection().close();
        } catch (Exception ex) {
            logger.error("connectionTimedOut()", ex);
        }
    }// connectionTimedOut

    public void connectionIdle(ConnectionEvent ce) {
        try {
            getTerminalIO().write("CONNECTION_IDLE");

            getTerminalIO().flush();
        } catch (IOException e) {
            logger.error(e, e);
        }
    }// connectionIdle

    public void connectionLogoutRequest(ConnectionEvent ce) {
        try {
            getTerminalIO().write("CONNECTION_LOGOUTREQUEST");
            getTerminalIO().flush();
        } catch (IOException e) {
            logger.error(e, e);
        }

    }// connectionLogout

    public void connectionSentBreak(ConnectionEvent ce) {
        try {
            getTerminalIO().write("CONNECTION_BREAK");
            getTerminalIO().flush();
        } catch (IOException e) {
            logger.error(e, e);
        }

    }

    public static Shell createShell() {
        return (Shell) getApplicationContext().getBean(BEAN_NAME);
    }

}
